$(document).ready(function() {
    $('#subjectSelect').change(function() {
        var subjectId = $(this).val();
        if (subjectId) {
            $.ajax({
                url: '${pageContext.request.contextPath}/teachers/' + ${teacher.userId} + '/subjects/' + subjectId + '/grades',
                method: 'GET',
                success: function(data) {
                    $('#scoresTable tbody').empty();
                    $.each(data, function(index, grade) {
                        var row = '<tr>' +
                            '<td>' + grade.studentId + '</td>' +
                            '<td><input type="text" class="form-control grade-input" data-student-id="' + grade.studentId + '" value="' + grade.grade + '"></td>' +
                            '<td><button class="btn btn-secondary edit-grade">编辑</button></td>' +
                            '</tr>';
                        $('#scoresTable tbody').append(row);
                    });
                }
            });
        } else {
            $('#scoresTable tbody').empty();
        }
    });

    $('#saveScores').click(function() {
        var grades = [];
        $('.grade-input').each(function() {
            var studentId = $(this).data('student-id');
            var grade = $(this).val();
            grades.push({studentId: studentId, grade: grade});
        });

        $.ajax({
            url: '${pageContext.request.contextPath}/teachers/' + ${teacher.userId} + '/subjects/' + $('#subjectSelect').val() + '/grades',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(grades),
            success: function(response) {
                alert('成绩已保存！');
                window.location.href = '${pageContext.request.contextPath}/teacherHome.jsp';
            }
        });
    });

    $('#addGradeForm').submit(function(event) {
        event.preventDefault();
        var newGrade = {
            studentId: $('#studentId').val(),
            grade: $('#grade').val(),
            subjectId: $('#subjectSelect').val()
        };

        $.ajax({
            url: '${pageContext.request.contextPath}/teachers/' + ${teacher.userId} + '/subjects/' + newGrade.subjectId + '/grades',
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(newGrade),
            success: function(response) {
                alert('新增成绩成功！');
                // 重新加载成绩表
                $('#subjectSelect').change();
            }
        });
    });
});
